/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package trab_sd;

import java.util.*;
import java.net.*;
import java.io.*;

public class FileListSender implements Runnable {
	private User localUser;
	private UserID dst;
	private Socket connection;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private boolean cont;
	
	public FileListSender ( User localUser, UserID dst ) {
		//Pega o usuario local e o destino da conexao
		this.localUser = localUser;
		this.dst = dst;
		//Tenta estabelecer a conexao e abrir os streams
		try {
			cont = true;
			connection = new Socket( dst.getName(), dst.getPort() );
			out = new ObjectOutputStream( connection.getOutputStream() );
			out.flush();
			in = new ObjectInputStream( connection.getInputStream() );
			//Estabelece o tempo maximo de inatividade como 50s
			connection.setSoTimeout( 50000 );
		}
		catch (  SocketTimeoutException | ConnectException ste) {
			if ( dst.equals(localUser.getServerID()) ) {
				localUser.removeOfflineUser(dst);
			}
			else {
			OfflineUserMsg of = new OfflineUserMsg( dst, localUser.getServerID());
			of.run();
			}
			cont = false;
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	public void run() {
		if (cont == false) return;
		try {
			//Envia mensagem indicando o envio da lista
			out.writeUTF("SENDING_FILE_LIST");
			out.flush();
			//espera resposta para o envio
			if ( !in.readUTF().equals("OK") ) throw new SocketTimeoutException();		//MUDAR INTERRUPCAO
			//envia a lista
			out.writeObject(localUser.getFileList());
			out.flush();
			//envia resposta de termino
			out.writeUTF("FINISHED");
			out.flush();
		}
		catch ( ConnectException ce) {
			OfflineUserMsg of = new OfflineUserMsg( dst, localUser.getServerID() );
			of.run();
		}
		
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
		finally {
			try {
				//fecha os streams
				in.close();
				out.close();
				
				//fecha a conexao
				connection.close();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		return;
	}
}
